#include "server_backend.h"
#include "network.h"
#include "error.h"
#include "cmd_code.h"

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<unistd.h>
#include<signal.h>
#include<sys/wait.h>
#include<arpa/inet.h>
#include<sys/socket.h>


int servfd;


//socket设置初始化
void sockOptInit(int servfd){
    int optval = 1;
    setsockopt(servfd,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof(optval));
}

int main(){
    //服务端启动时的初始化
    servfd = serverInit();
    sockOptInit(servfd);

    //等待客户端连接，这里用多进程实现
    int clntfd;
    struct sockaddr_in clnt_addr;
    socklen_t clnt_addr_len;
    while(1){
        printf("awaiting a connection...\n");
        clntfd = accept(servfd,(struct sockaddr *)&clnt_addr,&clnt_addr_len);
        if(clntfd == -1)
            continue;
        else    
            printf("new connection from %s:%d\n accepted\n", inet_ntoa(clnt_addr.sin_addr), ntohs(clnt_addr.sin_port));   
       
        while(1){
            int cmd_code = getClntCode(clntfd);
            printf("cmd_code:%d\n",cmd_code);
            if(cmd_code == CMD_CLOSE)
                break;
            serverResponse(clntfd,cmd_code);
        }
        networkClose(clntfd);
        printf("connection ends\n");

    }

    networkClose(servfd);
   
    return 0;
}

